
package projetomsn.Server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.SQLException;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * Essa classe roda o servidor
 */
public class RunServer implements ServerInterface {

    /**
     * Este atributo executa thread no servidor
     */
    private ExecutorService serverThread;
    private static Logger log = Logger.getLogger(RunServer.class.getName());
    //String language;
    //private ResourceBundle myResources;
    private static ResourceBundle myResources =
            ResourceBundle.getBundle("Properties.messages", Locale.getDefault());

    /**
     * Esse metodo cria uma pool para colocar thread do servidor
     */
    public synchronized void initializeServer() {

        serverThread = Executors.newCachedThreadPool();

        try {
            // Cria um novo socket para conexão
            ServerSocket newServerSocket =
                    new ServerSocket(12345, 100);


            //espera constante por clientes
            while (true) {
                System.out.println(myResources.getString("runserver.print.esperando.conexao"));
                // Espera um nova conexão do cliente
                Socket clientSocket = newServerSocket.accept();

                System.out.println(myResources.getString("runserver.print.conexao.porta") + clientSocket.getPort());
                // Cria uma nova thread para receber e enviar mensagens

                serverThread.execute(
                        new ServerConnectionThread(this, clientSocket));


            }

        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }

    /**
     * método da interface
     */
    public void messageReceived(String from, String message) {
    }

    /**
     * roda a aplicação
     */
    public static void main(String args[]) {
        try {
            ServerSettings.getServerDefaultSettings();

            RunServer server = new RunServer();

            server.initializeServer();
        } catch (SQLException ex) {
            //System.out.println(myResources.getString("runserver.print.problemas"));
        }
    }
}
